import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../screens/mine/model/comic_xxhistory_model.dart';
import '../utils/http_helper.dart';

class PaymentHistoryState {
  final List<ComicXxHistoryModel> records;
  final bool isLoading;
  final bool isLoadingMore;
  final bool hasMore;
  final String? error;
  final int currentPage;
  final int pageSize;

  const PaymentHistoryState({
    this.records = const [],
    this.isLoading = false,
    this.isLoadingMore = false,
    this.hasMore = true,
    this.error,
    this.currentPage = 1,
    this.pageSize = 20,
  });

  PaymentHistoryState copyWith({
    List<ComicXxHistoryModel>? records,
    bool? isLoading,
    bool? isLoadingMore,
    bool? hasMore,
    String? error,
    int? currentPage,
    int? pageSize,
  }) {
    return PaymentHistoryState(
      records: records ?? this.records,
      isLoading: isLoading ?? this.isLoading,
      isLoadingMore: isLoadingMore ?? this.isLoadingMore,
      hasMore: hasMore ?? this.hasMore,
      error: error,
      currentPage: currentPage ?? this.currentPage,
      pageSize: pageSize ?? this.pageSize,
    );
  }
}

class PaymentHistoryNotifier extends StateNotifier<PaymentHistoryState> {
  PaymentHistoryNotifier() : super(const PaymentHistoryState());

  final HttpUtil _httpUtil = HttpUtil();

  Future<void> loadPaymentHistory({bool isRefresh = false}) async {
    if (isRefresh) {
      state = state.copyWith(
        isLoading: true,
        error: null,
        currentPage: 1,
        hasMore: true,
      );
    } else {
      if (state.isLoading || state.isLoadingMore || !state.hasMore) return;
      state = state.copyWith(isLoadingMore: true, error: null);
    }

    try {
      print("🔄 About to call HttpUtil().getModel"); // 添加这行
      final response = await HttpUtil().getModel<List<ComicXxHistoryModel>>(
        'ComicMember/GetUserPaymentRecordList',
        params: {
          "PageSize": 10,
          "PageNo": isRefresh ? 1 : state.currentPage,
        },
        fromJson: (json) => (json as List)
            .map((item) => ComicXxHistoryModel.fromJson(item))
            .toList(),
      );

      print("response = $response");

      if (response?.status == 200 && response?.result != null) {
        final newComics = response!.result!;
        final hasMore = newComics.length >= 10;

        if (isRefresh || state.currentPage == 1) {
          state = state.copyWith(
            records: newComics,
            isLoading: false,
            error: null,
            hasMore: hasMore,
            currentPage: 1,
          );
        } else {
          state = state.copyWith(
            records: [...state.records, ...newComics],
            isLoadingMore: false,
            error: response.message,
            hasMore: hasMore,
          );
        }
      } else {
        state = state.copyWith(
          isLoading: false,
          isLoadingMore: false,
          error: '加载失败，请重试',
        );
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        isLoadingMore: false,
        error: 'Network error: ${e.toString()}',
      );
    }
  }

  Future<void> refresh() async {
    await loadPaymentHistory(isRefresh: true);
  }

  Future<void> loadMore() async {
    await loadPaymentHistory(isRefresh: false);
  }

  void clearError() {
    state = state.copyWith(error: null);
  }
}

final paymentHistoryProvider =
    StateNotifierProvider<PaymentHistoryNotifier, PaymentHistoryState>(
  (ref) => PaymentHistoryNotifier(),
);
